
package com.lmax.disruptor.demo;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.IgnoreExceptionHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;


public class MallDisruptor<T> {

    public static final Integer DEFAULT_SIZE = 4096 << 1 << 1;

    private static final Integer DEFAULT_CONSUMER_SIZE = Runtime.getRuntime().availableProcessors() << 1;

    private final Integer size;

    private DisruptorProvider<T> provider;

    private Integer consumerSize;

    private DisruptorConsumer<T> consumer;


    public MallDisruptor(final DisruptorConsumer<T> consumer, final Integer ringBufferSize) {
        this(consumer,
                DEFAULT_CONSUMER_SIZE,
                ringBufferSize);
    }


    public MallDisruptor(final DisruptorConsumer<T> consumer) {
        this(consumer, DEFAULT_CONSUMER_SIZE, DEFAULT_SIZE);
    }


    /**
     *
     * @param consumer the consumer factory
     * @param consumerSize    the consumer size
     * @param ringBufferSize  the ringBuffer size
     */
    public MallDisruptor(final DisruptorConsumer<T> consumer,
                         final int consumerSize,
                         final int ringBufferSize) {
        this.consumer = consumer;
        this.size = ringBufferSize;
        this.consumerSize = consumerSize;
        startup();
    }

    private void startup() {
        Disruptor<DataEvent<T>> disruptor = new Disruptor<>(new DisruptorEventFactory<>(),
                size,
                MallThreadFactory.create("disruptor_consumer_" + consumer.fixName(), false),
                ProducerType.MULTI,
                new BlockingWaitStrategy());
        DisruptorWorkHandler<T>[] workerPool = new DisruptorWorkHandler[consumerSize];
        for (int i = 0; i < consumerSize; i++) {
            workerPool[i] = new DisruptorWorkHandler<>(consumer);
        }
        disruptor.handleEventsWithWorkerPool(workerPool);
        disruptor.setDefaultExceptionHandler(new IgnoreExceptionHandler());
        disruptor.start();
        RingBuffer<DataEvent<T>> ringBuffer = disruptor.getRingBuffer();
        provider = new DisruptorProvider<>(ringBuffer, disruptor);
    }
    
    public DisruptorProvider<T> getProvider() {
        return provider;
    }
}
